package com.hechuan.interceptor;

import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

/**
 * 查询拦截器1
 */
public class QueryInterceptor1 implements InnerInterceptor {

    /**
     * 简单直接
     * 缺点：没有预编译sql条件 直接拼值。可能会造成sql注入
     */
    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) {
        // 原始sql：SELECT  id,name,age,address  FROM t_user
        String originSql = boundSql.getSql();
        System.out.println("originSql：" + originSql);

        // 修改后的sql
        String targetSql = "SELECT id,name,age,address FROM t_user WHERE age = 18";

        // 修改完成的sql 再设置回去
        PluginUtils.MPBoundSql mpBoundSql = PluginUtils.mpBoundSql(boundSql);
        mpBoundSql.sql(targetSql);
    }

}
